package cn.youframe.sample.fileupload;

import cn.youframe.comp.excel.Excel2EntityConfig;
import cn.youframe.comp.excel.ExcelReader;
import cn.youframe.frame.base.BaseCtrl;
import cn.youframe.frame.util.DateUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.FileOutputStream;
import org.apache.commons.io.FileUtils;
import org.apache.commons.fileupload.FileUpload;

import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.List;

/**
 * User: Administrator
 * DateTime: 12-6-28: 上午10:00
 */
@Controller
@RequestMapping(value = "/sample")
public class FileUploadCtrl extends BaseCtrl{
    /**
     * 上传单个文件
     * @param file
     * @return
     * @throws java.io.IOException
     */
    @RequestMapping(value = "/FileUploadCtrl!oneFileUpload.do", method = RequestMethod.POST)
    public String oneFileUpload(@RequestParam("upfile1") MultipartFile file,HttpServletRequest request) throws IOException {
        String message="";
        try{
            logger.info("上传文件："+file.getOriginalFilename());
            if (!file.isEmpty()) {
                FileUtils.copyInputStreamToFile(file.getInputStream(),new File("c:/upload/"+file.getOriginalFilename()));
//                copyFile(file.getInputStream(), file.getOriginalFilename());
            }
            message="上传成功："+file.getOriginalFilename();
        }catch (Exception e){
            message="上传失败："+e.getMessage();
            logger.error(message,e);
        }
        request.setAttribute("message",message);
        return "sample/fileupload/UploadResult";
    }

    /**
     * 多个文件上传
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/FileUploadCtrl!mutiFileUpload.do", method = RequestMethod.POST)
    public String mutiFileUpload(MultipartHttpServletRequest request) throws Exception {
        String message="";
        try{
            logger.info(request.getParameter("fileDesc"));
            Iterator<String> fileit=request.getFileNames();
            if(fileit!=null){
                while(fileit.hasNext()){
                    List<MultipartFile> filels= request.getFiles(fileit.next());
                    if(filels!=null){
                        for(MultipartFile mfile:filels){
                            FileUtils.copyInputStreamToFile(mfile.getInputStream(),new File("c:/upload/"+mfile.getOriginalFilename()));
                            message+=mfile.getOriginalFilename()+"\n";
                        }
                    }
                }
            }
            message+="\n上传成功";
        }catch (Exception e){
            message="上传失败："+e.getMessage();
            logger.error(message,e);
        }
        request.setAttribute("message",message);
        return "sample/fileupload/UploadResult";
    }

    /**
     * 文件下载
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/FileUploadCtrl!downloadFile.do", method = RequestMethod.POST)
    public String downloadFile(HttpServletRequest request,HttpServletResponse response) throws Exception {
        String message="";
        int flag=0;
        try{
            String filePath=request.getParameter("fileDesc");
            File downFile=new File(filePath);
            String fileName="";
            if(downFile!=null && downFile.exists()){
                fileName=downFile.getName();
                int blockSize=65000;
                byte[] abyte = new byte[blockSize];
                long l = downFile.length();
                response.reset();
//                response.setContentType("application/x-msdownload");
                response.setContentType("application/octet-stream;charset=UTF-8");
                response.setHeader("Content-Disposition", "attachment; filename=" +new String(fileName.getBytes(),"ISO8859_1"));
                response.addHeader("Content-Length", "" + l);
                FileInputStream fileinputstream = new FileInputStream(downFile);
                int k=0;
                while (k < l){
                    int j = fileinputstream.read(abyte, 0, blockSize);
                    k += j;
                    response.getOutputStream().write(abyte, 0, j);
                }
                fileinputstream.close();
                message="下载成功！";
            }else {
                flag=1;
                message="文件不存在！";
            }
        }catch (Exception e){
            flag=2;
            message="下载失败："+e.getMessage();
            logger.error(message,e);
        }
        if(flag>0){
            request.setAttribute("message",message);
            return "sample/fileupload/UploadResult";
        }else{
            return null;
        }
    }
    /**
     * 上传单个文件
     * @param file
     * @return
     * @throws java.io.IOException
     */
    @RequestMapping(value = "/FileUploadCtrl!readExcel.do", method = RequestMethod.POST)
    public String readExcel(@RequestParam("upfile1") MultipartFile file,HttpServletRequest request) throws IOException {
        String message="";
        try{
            logger.info("读取Excel文件："+file.getOriginalFilename());
            if (!file.isEmpty()) {
//                FileUtils.copyInputStreamToFile(file.getInputStream(),new File("c:/upload/"+file.getOriginalFilename()));
                InputStream input = file.getInputStream();
                Excel2EntityConfig config = new Excel2EntityConfig();
                String[] columns = {"name", "password", "birthday","phoneNo","certNo"};
                config.setColumns(columns);
                config.setFormater(new SimpleDateFormat("yyyy/MM/dd"));
                config.setCurrPosittion(2);
                config.setColStartPosittion(1);
                ExcelReader<ExcelEntity> excel = new ExcelReader<ExcelEntity>();
                excel.setExcel2EntityConfig(config);
                excel.InitExcelReader(input);
                try {
                    ExcelEntity entity = new ExcelEntity();
                    excel.setEntity(entity);
                    entity = excel.readLine();
                    while (entity != null) {
                        logger.info("Name=" + entity.getName() + ",Password=" + entity.getPassword() + ",Birthday=" + DateUtil.getThisDate("yyyy-MM-dd HH:mm:ss",entity.getBirthday())+",PhoneNo="+entity.getPhoneNo()+",CertNo="+entity.getCertNo());
                        ///保存实体代码
                        entity = new ExcelEntity();
                        excel.setEntity(entity);
                        entity = excel.readLine();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally{
                    input.close();
                }
            }
            message="Excel文件读取成功："+file.getOriginalFilename();
        }catch (Exception e){
            message="Excel文件读取失败："+e.getMessage();
            logger.error(message,e);
        }
        request.setAttribute("message",message);
        return "sample/fileupload/UploadResult";
    }

    /**
        * 写文件
        * @param in
        * @param fileName
        * @throws IOException
        */
    private void copyFile(InputStream in,String fileName) throws IOException{
        FileOutputStream fs = new FileOutputStream("c:/upload/" + fileName);
        byte[] buffer = new byte[1024 * 1024];
        int bytesum = 0;
        int byteread = 0;
        while ((byteread = in.read(buffer)) != -1) {
            bytesum += byteread;
            fs.write(buffer, 0, byteread);
            fs.flush();
        }
        fs.close();
        in.close();
    }
}
